using System;
using ConsentManagementProviderLib.Json;
using UnityEngine;

namespace ConsentManagementProviderLib.Android
{
	internal class CustomConsentClient : AndroidJavaProxy
	{
		private static readonly string NativeJavaInterfaceName = "com.sourcepoint.cmplibrary.consent.CustomConsentClient";

		private Action<GdprConsent> callback;

		internal GdprConsent customGdprConsent;

		public CustomConsentClient(Action<GdprConsent> callback)
			: base(new AndroidJavaClass(NativeJavaInterfaceName))
		{
			this.callback = callback;
		}

		private void transferCustomConsentToUnity(string spConsentsJson)
		{
			CmpDebugUtil.Log("transferCustomConsentToUnitySide c#-side custom consent ->" + spConsentsJson.ToString());
			SpCustomConsentAndroid spCustomConsentAndroid = null;
			try
			{
				spCustomConsentAndroid = JsonUnwrapper.UnwrapSpCustomConsentAndroid(spConsentsJson);
			}
			catch (Exception ex)
			{
				Debug.LogError("Something went wrong while parsing the json data; null will be returned. \n Exception message: " + ex.Message);
			}
			finally
			{
				if (spCustomConsentAndroid == null)
				{
					callback?.Invoke(null);
				}
				else
				{
					SpGdprConsent spGdprConsent = JsonUnwrapper.UnwrapSpGdprConsentAndroid(spCustomConsentAndroid.gdpr);
					customGdprConsent = spGdprConsent.consents;
					callback?.Invoke(customGdprConsent);
				}
			}
		}
	}
}
